import paho.mqtt.client as mqtt
import json
import pymysql
from datetime import datetime


def on_connect(client, userdata, flags, rc):
    if rc == 0:
        print("Connected successfully.")
    else:
        print("Connected with result code " + str(rc))
    #client.subscribe("#") #39的
    #client.subscribe("gw/#")
    # 订阅主题
    client.subscribe("gw/devices/coordinate")

# def on_message(client, userdata, msg):   #39的数据格式
#     topic = msg.topic
#     #print(msg.topic + " " + str(msg.payload))
#     # 将字节串解码成字符串
#     if deviceid in topic:
#         print("123")
#         # 将字节串解码成字符串
#         message_str = msg.payload.decode()
#         # 解析JSON数据
#         message = json.loads(message_str)
#         # 安全地获取位置信息，如果'position'键不存在，则返回空字典
#         position = message.get('position', {})
#         # 提取x, y, z坐标
#         x = position.get('x', 'NaN')
#         y = position.get('y', 'NaN')
#         z = position.get('z', 'NaN')
#         # 检查坐标是否为有效数值
#         if not (x == 'NaN' or y == 'NaN' or z == 'NaN'):
#             # 打印坐标
#             print(f"X: {x}, Y: {y}, Z: {z}")
#             update_time_new = datetime.now()
#             x = x*1000
#             y = y * 1000
#             z = z * 1000
#             cursor.execute(
#                 f"UPDATE map_device SET x={x}, y={y},z={z}, update_time='{update_time_new}'WHERE device_id = 'GW{deviceid}'")
#             conn.commit()
#             #print(f"UPDATE map_device SET x={x}, y={y},z={z}, update_time='{update_time_new}'WHERE device_id = 'GW{deviceid}'")
#         else:
#             print("xyz not available")

# def on_message(client, userdata,msg):
#     # 将字节串解码成字符串
#     message_str = msg.payload.decode()
#     # 解析JSON数据
#     message = json.loads(message_str)
#     print(message)
#     id = message.get('id', {})
#     print(id)
#     if id == deviceid:
#         x = message.get('x', 'NaN')
#         y = message.get('y', 'NaN')
#         z = message.get('z', 'NaN')
#         # 检查坐标是否为有效数值
#         if not (x == 'NaN' or y == 'NaN' or z == 'NaN'):
#
#              # 打印坐标
#             print(f"X: {x}, Y: {y}, Z: {z}")
#             update_time_new = datetime.now()
#             cursor.execute(
#                  f"UPDATE map_device SET x={x}, y={y},z={z}, update_time='{update_time_new}'WHERE device_id = '{deviceid}'")
#             conn.commit()
#
#         else:
#             print("xyz not available")

def on_message(client, userdata, msg):
    # 将消息写入文件
    with open(outfile, "a") as file:  # 以追加模式打开文件
        print("1")
        message = f"Topic: {msg.topic}, Message: {msg.payload.decode()}\n"
        file.write(message)
    print(f"Message received and written to {outfile}: {message.strip()}")


# MySQL数据库连接
# 数据库配置
# config = {
#     'host': '192.168.3.90',
#     'user': 'tester',
#     'password': 'tester1234',
#     'database': 'gateway',
#     'charset': 'utf8mb4',
# }
#
# conn = pymysql.connect(**config)
# cursor = conn.cursor()
outfile = "mqtt_messages.txt"  # 输出文件名
#deviceid = '4807'
#deviceid = '50ad'
# 创建MQTT客户端实例
client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message

#client.connect("192.168.3.88", 1883, 60)
#client.connect("192.168.3.39", 1883, 60)
client.connect("218.108.8.218", 1883, 60)
# 设置用户名和密码
client.username_pw_set("gwzauser", "gwza@2024")

# 连接到MQTT服务器
#client.connect("218.108.8.218", 1883, 60)

#client.loop_forever()
client.loop_start()
# 订阅主题
#client.subscribe("gw/devices/coordinate")
# 程序结束前关闭数据库连接
# import atexit
# atexit.register(conn.close)

# 保持程序运行
try:
    while True:
        pass
except KeyboardInterrupt:
    print("Program terminated by user")

